#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include <functional>

namespace ThreadModule
{
    template <typename T>
    // 把任务和名字传过来
    using func_t = std::function<void(T&, std::string name)>;

    
    template <typename T>
    class Thread
    {
    public:
        Thread(func_t<T> func, T &data, std::string name = "none-name")
            : _func(func), _data(data), _name(name), _is_run(true)
        {
        }

        void Excute()
        {
            _func(_data, _name);
        }

        static void *fun(void *arg)
        {
            Thread<T> *self = static_cast<Thread<T> *>(arg);
            self->Excute();
            return nullptr;
        }

        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, fun, this);
            if (!n)
            {
                _is_run = false;
                return true;
            }
            else
            {
                return false;
            }
        }

        void Detach()
        {
            if (!_is_run)
            {
                pthread_detach(_tid);
            }
        }

        void Join()
        {
            if (!_is_run)
            {
                pthread_join(_tid, nullptr);
            }
        }

        std::string name()
        {
            return _name;
        }

        void Stop()
        {
            _is_run = true;
        }

        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        std::string _name;
        func_t<T> _func;
        T &_data;
        bool _is_run;
    };

} // namespace ThreadModule
